package com.h3bpm.kumhosunny.comment.utils;

import com.h3bpm.base.config.PortalPropertiesUtil;
import com.h3bpm.base.util.AppUtility;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author qinyt
 * @className FileUploadUtil
 * @description 文件上传工具类
 * @date 2019/3/4 11:54
 **/
public class FileUploadUtil {
    /**
     * 默认允许上传附件的最大大小,10MB(10_485_760)
     */
    private static final int DEFAULT_UPLOAD_FILE_MAXSIZE = 10 * 1024 * 1024;

    /**
     * 默认允许上传图片的最大大小,2MB(2_097_152)
     */
    private static final int DEFAULT_UPLOAD_IMAGE_MAXSIZE = 2 * 1024 * 1024;

    /**
     * 替换文件名中不合法的字符
     * 
     * @param fileName
     * @return 新文件名
     */
    public static String replaceFileName(String fileName) {
        String newFileName = "";

        if (StringUtils.isEmpty(fileName)) {
            return newFileName;
        }

        try {
            // 截取后缀名
            String exStr = fileName.substring(fileName.lastIndexOf("."));
            // 文件名，不含后缀
            newFileName = fileName.substring(0, fileName.lastIndexOf("."));

            String[] beforeString = {"#", "~", "&", "!", "@", "$", "%", "^", "*", "(", ")", "?", "{", "}", "."};
            String[] afterString = {"＃", "～", "＆", "！", "＠", "＄", "％", "︿", "＊", "（", "）", "？", "｛", "｝", "．"};
            for (int i = 0; i < beforeString.length; i++) {
                newFileName = newFileName.replace(beforeString[i], afterString[i]);
            }
            newFileName += exStr;
        } catch (RuntimeException ex) {
            newFileName = fileName;
        }
        return newFileName;
    }
    
    /**
     * 获取指定文件在临时目录里的路径
     * @param fileName
     * @return 指定文件的路径
     */
    public static String getFilePath(String fileName) {
        HttpServletRequest request =
            ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        String currentPath = request.getServletContext().getRealPath("/");
        String filePath = currentPath + File.separator + "Portal" + File.separator + "TempFiles" + File.separator;
        String savePath = filePath + AppUtility.getEngine().getEngineConfig().getCode() + File.separator;

        // 文件路径
        File fileFolder = new File(savePath);
        if (!fileFolder.exists()) {
            fileFolder.mkdirs();
        }

        return savePath + fileName;
    }

    public static boolean writeToFile(MultipartFile file, String filePath) throws IOException {
        File tmpFile = new File(filePath);
        
        if (!tmpFile.exists()) {
                FileUtils.writeByteArrayToFile(tmpFile, file.getBytes(), false);
        }

        return true;
    }

    /**
     * 根据上传类型（图片形式/附件形式）得到允许上传文件的最大大小
     * 
     * @param uploadByImage
     * @return 允许上传的文件最大限制
     */
    public static int getAllowedMaxSize(boolean uploadByImage) {
        String maxSize;
        if (uploadByImage) {
            maxSize = PortalPropertiesUtil.getProperty("maxUploadImageSize");
        } else {
            maxSize = PortalPropertiesUtil.getProperty("maxUploadFileSize");
        }
        // 允许上传的文件大小默认为图片的大小
        int allowedSize = DEFAULT_UPLOAD_IMAGE_MAXSIZE;
        // 如果配置文件有配置，则以配置文件为准
        if (StringUtils.isNotBlank(maxSize)) {
            allowedSize = Integer.valueOf(maxSize);
            return allowedSize;
        }
        // 如果配置文件没有配置，且上传类型为附件形式
        if (!uploadByImage) {
            allowedSize = DEFAULT_UPLOAD_FILE_MAXSIZE;
        }

        return allowedSize;
    }
}
